import type { ResponseData } from '@/utils/types.d';
import { SUCCESS_CODE } from '@/utils/types.d';
import request from '@/utils/request';
import type {
  ChargeRuleTableItem,
  CheckChargeRule,
  CreateChargeRule,
  UpdateChargeRuleType,
} from './types.d';

export async function queryChargeRules(
  data: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: ChargeRuleTableItem[];
}> {
  const res: ResponseData<{ total: number; data: ChargeRuleTableItem[] }> = await request(
    '/api/charge-rule/v1.0.0/charge-rules',
    {
      params: {
        data,
        sort,
      },
    },
  );
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.data };
  return { success: false, total: 0, data: [] };
}

export async function createChargeRule(params: CreateChargeRule) {
  const res = await request('/api/charge-rule/v1.0.0/charge-rule', {
    method: 'POST',
    data: params,
  });
  if (res?.code === SUCCESS_CODE)
    return {
      data: res.data,
      success: true,
      message: '添加成功',
    };
  return { data: res?.data, success: false, message: res?.message || '添加失败' };
}

export async function testChargeRule(params: CheckChargeRule) {
  const res = await request('/api/charge-rule/v1.0.0/testChargeRule', {
    method: 'POST',
    data: params,
  });
  if (res?.code === SUCCESS_CODE)
    return {
      data: res.data,
      success: true,
      message: '计算成功',
    };
  return { data: res?.data, success: false, message: res?.message || '计算失败' };
}

export async function updateChargeRule(id: string, newInfo: UpdateChargeRuleType) {
  if (!id || !newInfo || Object.keys(newInfo).length === 0)
    return { success: false, message: '更新失败，请填入需要更新的信息' };
  const res: ResponseData<null> = await request(`/api/charge-rule/v1.0.0/charge-rule/${id}`, {
    method: 'PUT',
    data: newInfo,
  });
  if (res?.code === SUCCESS_CODE) {
    return { success: true, data: res.data, message: '更新成功' };
  }
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}

export async function removeChargeRule(id: string) {
  const res: ResponseData<null> = await request(`/api/charge-rule/v1.0.0/charge-rule/${id}`, {
    method: 'DELETE',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}
